<template>
  <div class="task-detail">
    <header class="task-header">
      <el-button type="primary" @click="closePage">关闭</el-button>
    </header>
    <div class="task-body">
      <div class="task-sider">
        <el-scrollbar height="100%">
          <div class="measure-point">
            <DiagramPicker
              v-if="monitorDevice && monitorDevice.fileType === 2"
              :monitorDevice="monitorDevice"
              :otherPoints="allPoints"
              :isPreview="true"
              backgroundColor="rgba(255, 255, 255, .9)"
            />

            <ImagePicker
              v-if="monitorDevice && monitorDevice.fileType === 1"
              :monitorDevice="monitorDevice"
              :otherPoints="allPoints"
              :isPreview="true"
              backgroundColor="rgba(255, 255, 255, .9)"
            />
          </div>
          <div class="device-info">
            <el-descriptions title="" size="small" :column="2">
              <el-descriptions-item label="设备名称">{{
                monitorDevice.deviceName
              }}</el-descriptions-item>
              <!-- <el-descriptions-item label="设备ID">{{
                taskData?.monitorDeviceId
              }}</el-descriptions-item> -->

              <el-descriptions-item label="设备类型">
                <dict-tag
                  v-if="monitorDevice.deviceType !== undefined"
                  :type="DICT_TYPE.MONITOR_DEVICE_TYPE"
                  :value="monitorDevice.deviceType"
                />
              </el-descriptions-item>
              <el-descriptions-item label="设备型号">{{
                monitorDevice.deviceModel
              }}</el-descriptions-item>
              <!-- <el-descriptions-item label="出厂日期">{{
                monitorDevice.productionDate
              }}</el-descriptions-item> -->
              <el-descriptions-item label="生产厂家">{{
                monitorDevice.manufacturer
              }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="measure-tree">
            <el-tree
              ref="treeRef"
              style="max-height: 100%"
              :data="signalTreeData"
              show-checkbox
              default-expand-all
              @check="handleCheckChange"
            />
          </div>
        </el-scrollbar>
      </div>
      <div class="task-content">
        <el-scrollbar height="100%">
          <div class="signla-chart-list">
            <div
              class="signal-chart-item"
              v-for="(widgetData, index) in checkedSignalList"
              :key="index"
            >
              <div class="signal-chart-title">
                {{ widgetData.measureData.name }}
                <span>({{ widgetData.options.data.signal.label }})</span>
              </div>
              <div class="signal-chart-content">
                <component
                  :is="getChartComponent(widgetData.key)"
                  :widgetOptions="widgetData.options"
                  :isPreview="true"
                />
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { MonitorDeviceApi } from '@/api/vmiot/monitordevice'
import { TaskApi } from '@/api/vmiot/task'
import DiagramPicker from '@/views/vmiot/task/DiagramPicker.vue'
import ImagePicker from '@/views/vmiot/task/ImagePicker.vue'
import { componentMap } from '../bigscreen/designer/widget/widgetMap'
import { useMqttStore } from '@/store/modules/mqttStore'
import { DICT_TYPE } from '@/utils/dict'

const { query } = useRoute() // 查询参数

const taskData = ref<any>()
const monitorDeviceList = ref<any[]>([])

const checkedSignalList = ref<any[]>([])
const treeRef = ref()
const tenantId = ref()

const getDetail = async (id) => {
  if (!id) {
    return
  }
  const res = await TaskApi.getTaskByShare(id)
  if (res.content) {
    res.content = JSON.parse(res.content)
  }
  taskData.value = res
  tenantId.value = res.tenantId

  getMonitorDeviceList()
}

const getMonitorDeviceList = async () => {
  monitorDeviceList.value = await MonitorDeviceApi.getAllMonitorDeviceListByShare(tenantId.value)
}

const allPoints = computed(() => {
  return taskData.value?.content?.nodes.filter((item) => item.type === 'output')
})

const monitorDevice = computed<any>(() => {
  return monitorDeviceList.value.find((item) => item.id == taskData.value?.monitorDeviceId) || {}
})

const signalTreeData = computed(() => {
  const nodes = taskData.value?.content?.nodes || []

  return nodes
    .filter((node) => node.type === 'output')
    .map((node) => {
      const measureData = node.data?.measureData
      const signals = measureData?.signalList || []

      return {
        label: measureData?.name || '未命名测点',
        measureId: node.id,
        children: signals.map((signal) => ({
          label: signal.signalLabel || signal.signalName,
          ...signal,
          measureData: measureData
        }))
      }
    })
})

const getChartComponent = (key) => {
  return componentMap[key]
}

const closePage = () => {
  window.close()
}

const chartStyles = {
  backgroundColor: '#E4E7ED',
  lineColor: '#58B8FB',
  lineWidth: 2,
  lineSmooth: true,
  lineAreaStyle: true,
  legendColor: 'rgba(255, 215, 0, 1)',
  legendFontSize: 12,
  legendFontColor: '#fff',
  toolboxIconColor: '#fff',
  areaStyle: false,
  barColor: '#188df0',
  titleColor: '#333',
  titleFontSize: 16,
  subtitleColor: '#333',
  subtitleFontSize: 16,
  xLineColor: '#999',
  xFontColor: '#333',
  xFontSize: 12,
  xSplitLine: false,
  yLineColor: '#999',
  yFontColor: '#333',
  yFontSize: 12,
  ySplitLine: false,
  yNameFontColor: '#333',
  yNameFontSize: 12,
  viewFontColor: '#333',
  viewFontSize: 12
}

const handleCheckChange = () => {
  const nodes = treeRef.value?.getCheckedNodes(true) || []

  const widgetSignal: any[] = []
  nodes.forEach((node) => {
    widgetSignal.push({
      key: `widget-chart-${node.signalType.toLowerCase()}`,
      options: {
        setup: chartStyles,
        data: {
          signal: node
        }
      },
      measureData: node.measureData
    })

    if (node.signalType === 'STATP') {
      widgetSignal.push({
        key: `widget-chart-${node.signalType.toLowerCase()}-history`,
        options: {
          setup: chartStyles,
          data: {
            signal: node
          }
        },
        measureData: node.measureData
      })
    }
  })
  checkedSignalList.value = widgetSignal

  console.log(checkedSignalList.value)
}

onMounted(() => {
  const id = query.id as unknown as number
  getDetail(id)
  const mqttStore = useMqttStore()
  mqttStore.connect()
})
</script>
<style lang="scss">
.task-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #dfecff url('@/assets/images/task-bg.png') center top / 100% auto no-repeat;

  .task-header {
    height: 50px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-radius: 12px 12px 0px 0px;
  }

  .task-body {
    flex: 1;
    min-height: 0;
    display: flex;
  }

  .task-sider {
    width: 375px;
    height: 100%;
    padding-top: 10px;
    padding-left: 10px;
    display: flex;
    flex-direction: column;

    min-height: 600px;
    overflow-y: auto;

    .measure-point {
      border-radius: 6px;
      height: 300px;
      overflow: hidden;
    }

    .device-info {
      margin-top: 15px;
      .el-descriptions__body {
        border-radius: 6px;
        padding: 10px;
        background: rgb(228, 231, 237);
      }
    }

    .measure-tree {
      min-height: 300px;
      margin-top: 15px;

      .el-tree {
        background: rgb(228, 231, 237);
        border-radius: 6px;
      }
    }
  }

  .task-content {
    flex: 1;
    min-width: 0;
    height: 100%;
  }

  .signla-chart-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;

    padding: 10px;
  }

  .signal-chart-item {
    background: rgb(228, 231, 237);
    border: 1px solid #ddd;
    height: 450px;
    padding: 10px;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    .signal-chart-title {
      height: 30px;
      line-height: 30px;
      position: relative;
      padding-left: 15px;
      font-size: 20px;
      margin-bottom: 10px;
      span {
        font-size: 16px;
        color: #666;
      }

      &::before {
        content: '';
        width: 4px;
        height: 18px;
        background-color: #188df0;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .signal-chart-content {
      flex: 1;
      min-height: 0;
      border-radius: 8px;
      overflow: hidden;
    }
  }
}
</style>
